<template>
  <div class="server-monitor">
    <div class="header">
      <h2>服务器性能监控</h2>
      <div class="refresh-info">
        <span>最后更新: {{ lastUpdateTime }}</span>
        <el-button @click="refreshData" :loading="loading" size="small">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 系统概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon cpu-icon">
                <el-icon size="24"><Cpu /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ systemInfo.cpu }}%</div>
                <div class="metric-label">CPU使用率</div>
              </div>
            </div>
            <div class="metric-progress">
              <el-progress :percentage="systemInfo.cpu" :color="getProgressColor(systemInfo.cpu)" :show-text="false" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon memory-icon">
                <el-icon size="24"><Monitor /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ systemInfo.memory }}%</div>
                <div class="metric-label">内存使用率</div>
              </div>
            </div>
            <div class="metric-progress">
              <el-progress :percentage="systemInfo.memory" :color="getProgressColor(systemInfo.memory)" :show-text="false" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon disk-icon">
                <el-icon size="24"><Folder /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ systemInfo.disk }}%</div>
                <div class="metric-label">磁盘使用率</div>
              </div>
            </div>
            <div class="metric-progress">
              <el-progress :percentage="systemInfo.disk" :color="getProgressColor(systemInfo.disk)" :show-text="false" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="metric-card">
            <div class="metric-content">
              <div class="metric-icon network-icon">
                <el-icon size="24"><Connection /></el-icon>
              </div>
              <div class="metric-info">
                <div class="metric-value">{{ systemInfo.network }}</div>
                <div class="metric-label">网络流量</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 服务状态 -->
    <div class="services-section">
      <el-card>
        <template #header>
          <span>服务状态</span>
        </template>
        
        <el-table :data="services" style="width: 100%" stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="name" label="服务名称" />
          <el-table-column prop="status" label="运行状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'running' ? 'success' : 'danger'">
                {{ scope.row.status === 'running' ? '运行中' : '已停止' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="port" label="端口" />
          <el-table-column prop="uptime" label="运行时长" />
          <el-table-column prop="cpu" label="CPU占用" />
          <el-table-column prop="memory" label="内存占用" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                size="small" 
                :type="scope.row.status === 'running' ? 'danger' : 'success'"
                @click="toggleService(scope.row)"
              >
                {{ scope.row.status === 'running' ? '停止' : '启动' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 系统日志 -->
    <div class="logs-section">
      <el-card>
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>系统日志</span>
            <el-button size="small" @click="clearLogs">清空日志</el-button>
          </div>
        </template>
        
        <div class="log-container">
          <div 
            v-for="log in systemLogs" 
            :key="log.id" 
            class="log-item"
            :class="log.level"
          >
            <span class="log-time">{{ log.time }}</span>
            <span class="log-level">{{ log.level.toUpperCase() }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Refresh, Cpu, Monitor, Folder, Connection } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const lastUpdateTime = ref('')

const systemInfo = ref({
  cpu: 45,
  memory: 62,
  disk: 38,
  network: '2.5 MB/s'
})

const services = ref([
  {
    id: 1,
    name: 'Web服务器',
    status: 'running',
    port: '80',
    uptime: '15天 3小时',
    cpu: '12%',
    memory: '256MB'
  },
  {
    id: 2,
    name: 'API服务',
    status: 'running',
    port: '3000',
    uptime: '15天 3小时',
    cpu: '8%',
    memory: '128MB'
  },
  {
    id: 3,
    name: '数据库服务',
    status: 'running',
    port: '3306',
    uptime: '15天 3小时',
    cpu: '25%',
    memory: '512MB'
  },
  {
    id: 4,
    name: 'Redis缓存',
    status: 'stopped',
    port: '6379',
    uptime: '-',
    cpu: '0%',
    memory: '0MB'
  }
])

const systemLogs = ref([
  {
    id: 1,
    time: '2025-09-15 00:35:12',
    level: 'info',
    message: '系统启动完成'
  },
  {
    id: 2,
    time: '2025-09-15 00:35:15',
    level: 'info',
    message: 'Web服务器启动成功，监听端口80'
  },
  {
    id: 3,
    time: '2025-09-15 00:35:18',
    level: 'warning',
    message: 'CPU使用率较高，当前45%'
  },
  {
    id: 4,
    time: '2025-09-15 00:35:20',
    level: 'error',
    message: 'Redis服务连接失败'
  },
  {
    id: 5,
    time: '2025-09-15 00:35:25',
    level: 'info',
    message: '数据库连接正常'
  }
])

let refreshTimer = null

const updateLastTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  lastUpdateTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const getProgressColor = (percentage) => {
  if (percentage < 50) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

const refreshData = async () => {
  loading.value = true
  
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟数据更新
  systemInfo.value = {
    cpu: Math.floor(Math.random() * 100),
    memory: Math.floor(Math.random() * 100),
    disk: Math.floor(Math.random() * 100),
    network: `${(Math.random() * 10).toFixed(1)} MB/s`
  }
  
  updateLastTime()
  loading.value = false
  ElMessage.success('数据刷新成功')
}

const toggleService = (service) => {
  service.status = service.status === 'running' ? 'stopped' : 'running'
  
  const action = service.status === 'running' ? '启动' : '停止'
  ElMessage.success(`${service.name} ${action}成功`)
  
  // 添加日志
  const newLog = {
    id: Date.now(),
    time: new Date().toLocaleString().replace(/\//g, '-'),
    level: 'info',
    message: `${service.name} 已${action}`
  }
  systemLogs.value.unshift(newLog)
}

const clearLogs = () => {
  systemLogs.value = []
  ElMessage.success('日志已清空')
}

onMounted(() => {
  updateLastTime()
  // 每30秒自动刷新数据
  refreshTimer = setInterval(() => {
    refreshData()
  }, 30000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.server-monitor {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.refresh-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.refresh-info span {
  color: #666;
  font-size: 14px;
}

.overview-section {
  margin-bottom: 20px;
}

.metric-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.metric-card:hover {
  transform: translateY(-2px);
}

.metric-content {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.metric-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
}

.cpu-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.memory-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.disk-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.network-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.metric-label {
  font-size: 14px;
  color: #666;
}

.metric-progress {
  margin-top: 10px;
}

.services-section {
  margin-bottom: 20px;
}

.logs-section {
  margin-bottom: 20px;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
}

.log-item {
  display: flex;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #666;
  margin-right: 10px;
  min-width: 140px;
}

.log-level {
  margin-right: 10px;
  min-width: 60px;
  font-weight: bold;
}

.log-item.info .log-level {
  color: #409EFF;
}

.log-item.warning .log-level {
  color: #E6A23C;
}

.log-item.error .log-level {
  color: #F56C6C;
}

.log-message {
  flex: 1;
  color: #333;
}

/* 滚动条样式 */
.log-container::-webkit-scrollbar {
  width: 6px;
}

.log-container::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.log-container::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}
</style>
